package com.czl.module_user.viewmodel

import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.RegexUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.binding.command.BindingConsumer
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.CarItem
import com.czl.base.data.bean.ImgRspBean
import com.czl.base.data.bean.RoomBean
import com.czl.base.data.bean.UserInfo
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper

class UserInfoViewModel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {

    private lateinit var userInfo: UserInfo
    val uc = UiChangeEvent()

    var userId = ""
    var avatarUrl = ObservableField("")
    var faceUrl = ObservableField("")
    var nickName = ObservableField("")
    var name = ObservableField("")
    var gender = ObservableInt(0)
    var phone = ObservableField("")
    var idCard = ObservableField("")
    var birthday = ObservableField("")
    var email = ObservableField("")
    var company = ObservableField("")
    var depart = ObservableField("")

    class UiChangeEvent {
        val choiceImgEvent: SingleLiveEvent<Int> = SingleLiveEvent()
        val choiceGenderEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val choiceBirthdayEvent: SingleLiveEvent<Void> = SingleLiveEvent()
        val loadCarsCompleteEvent: SingleLiveEvent<List<CarItem>> = SingleLiveEvent()
        val loadRoomsEvent: SingleLiveEvent<List<RoomBean>> = SingleLiveEvent()
    }

    val onNickNameChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        nickName.set(it)
    })
    val onIdCardChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        idCard.set(it)
    })
    val onEmailChangeCommand: BindingCommand<String> = BindingCommand(BindingConsumer {
        email.set(it)
    })
    val onAvatarClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceImgEvent.postValue(IMG_HEAD)
    })
    val onGenderClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceGenderEvent.call()
    })
    val onBirthdayClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceBirthdayEvent.call()
    })

    val onSubmitClickCommand: BindingCommand<Any> = BindingCommand(BindingAction {
        changeUserInfo()
    })

    val onImageClick: BindingCommand<Any> = BindingCommand(BindingAction {
        uc.choiceImgEvent.postValue(IMG_FACE)
    })

    fun getUserInfo() {
        model.getLocalUserInfo()?.let {
            userId = it.userId
            avatarUrl.set(it.avatar)
            nickName.set(it.nickName)
            name.set(it.userName)
            gender.set(it.sex)
            phone.set(it.phonenumber)
            idCard.set(it.idCard)
            birthday.set(it.birthday)
            email.set(it.email)
            faceUrl.set(it.faceUrl)
            company.set(it.companyName)
            depart.set(it.deptName)
        }

    }

    fun uploadHeadImg(imgSrc: String, type: Int) {
        model.apply {
            uploadHeadImg("user", imgSrc, "")
                .compose(RxThreadHelper.rxSchedulerHelper(this@UserInfoViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<ImgRspBean>>() {
                    override fun onResult(t: BaseBean<ImgRspBean>) {
                        dismissLoading()
                        if (t.data == null) return
                        if (t.code == 200) {
                            when (type) {
                                IMG_HEAD -> avatarUrl.set(t.data?.url)
                                IMG_FACE -> faceUrl.set(t.data?.url)
                            }
                        } else {
                            showErrorToast(t.msg)
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        showErrorToast(msg)
                    }

                })
        }
    }

    private fun changeUserInfo() {
        if (!email.get().isNullOrBlank()) {
            if (!RegexUtils.isEmail(email.get())) {
                showErrorToast("邮箱格式错误")
                return
            }
        }
        if (!idCard.get().isNullOrBlank()) {
            if (!RegexUtils.isIDCard18(idCard.get())) {
                showErrorToast("身份证号格式错误")
                return
            }
        }

        model.apply {
            changeUserInfo(
                mapOf(
                    "userId" to userId,
                    "avatar" to avatarUrl.get().orEmpty(),
                    "birthday" to birthday.get().orEmpty(),
                    "email" to email.get().orEmpty(),
                    "phonenumber" to phone.get().orEmpty(),
                    "faceUrl" to faceUrl.get().orEmpty(),
                    "idCard" to idCard.get().orEmpty(),
                    "nickName" to nickName.get().orEmpty(),
                    "sex" to gender.get().toString(),
                )
            )
                .compose(RxThreadHelper.rxSchedulerHelper(this@UserInfoViewModel))
                .doOnSubscribe { showLoading() }
                .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                    override fun onResult(t: BaseBean<Any?>) {
                        dismissLoading()
                        showNormalToast(t.msg)
                        if (t.code == 200) {
                            LiveBusCenter.postModifyUserInfoEvent("")
                        }
                    }

                    override fun onFailed(msg: String?) {
                        dismissLoading()
                        LogUtils.i(msg)
                        showNormalToast(msg)
                    }

                })
        }
    }

    companion object {
        const val IMG_HEAD = 101
        const val IMG_FACE = 100
    }
}